package com.myc.train.business.service;
import java.math.BigDecimal;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myc.train.business.domain.DailyTrain;
import com.myc.train.business.domain.TrainStation;
import com.myc.train.business.enums.SeatTypeEnum;
import com.myc.train.business.enums.TrainTypeEnum;
import com.myc.train.common.resp.PageResp;
import com.myc.train.common.utils.SnowUtil;
import com.myc.train.business.domain.DailyTrainTicket;
import com.myc.train.business.domain.DailyTrainTicketExample;
import com.myc.train.business.mapper.DailyTrainTicketMapper;
import com.myc.train.business.req.DailyTrainTicketQueryReq;
import com.myc.train.business.req.DailyTrainTicketSaveReq;
import com.myc.train.business.resp.DailyTrainTicketQueryResp;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

@Service
public class DailyTrainTicketService {


    private static final Logger LOG = LoggerFactory.getLogger(DailyTrainStationService.class);
    @Resource
    private DailyTrainTicketMapper dailyTrainTicketMapper;

    @Resource
    private TrainStationService trainStationService;

    @Resource
    private DailyTrainSeatService dailyTrainSeatService;

    public void save(DailyTrainTicketSaveReq req){
        DateTime now = DateTime.now();
        DailyTrainTicket dailyTrainTicket = BeanUtil.copyProperties(req, DailyTrainTicket.class);

        if(ObjectUtil.isNull(dailyTrainTicket.getId())){
            dailyTrainTicket.setId(SnowUtil.getSnowflakeNextId());
            dailyTrainTicket.setCreateTime(now);
            dailyTrainTicket.setUpdateTime(now);
            dailyTrainTicketMapper.insert(dailyTrainTicket);
        }else{
            dailyTrainTicket.setUpdateTime(now);
            dailyTrainTicketMapper.updateByPrimaryKey(dailyTrainTicket);
        }
    }

//    @Cacheable(value = "DailyTrainTicketService.queryList")
    public PageResp<DailyTrainTicketQueryResp> queryList(DailyTrainTicketQueryReq req){
       //定义查询条件
        DailyTrainTicketExample dailyTrainTicketExample = new DailyTrainTicketExample();
        //根据id倒序排序
        dailyTrainTicketExample.setOrderByClause("id desc");
        //创建查询对象
        DailyTrainTicketExample.Criteria criteria = dailyTrainTicketExample.createCriteria();
        //不为空则对其新增查询条件
        if(ObjectUtil.isNotEmpty(req.getDate())){
            criteria.andDateEqualTo(req.getDate());
        }
        if(ObjectUtil.isNotEmpty(req.getTrainCode())){
            criteria.andTrainCodeEqualTo(req.getTrainCode());
        }
        if(ObjectUtil.isNotEmpty(req.getStart())){
            criteria.andStartEqualTo(req.getStart());
        }
        if(ObjectUtil.isNotEmpty(req.getEnd())){
            criteria.andEndEqualTo(req.getEnd());
        }

        //新增分页信息
        PageHelper.startPage(req.getPage(),req.getSize());
        //根据条件查询结果
        List<DailyTrainTicket> dailyTrainTickets = dailyTrainTicketMapper.selectByExample(dailyTrainTicketExample);
        //new一个PageInfo并将结果放进来
        PageInfo<DailyTrainTicket> dailyTrainTicketPageInfo = new PageInfo<>(dailyTrainTickets);
        //类拷贝
        List<DailyTrainTicketQueryResp> queryResps = BeanUtil.copyToList(dailyTrainTickets, DailyTrainTicketQueryResp.class);
        //new一个PageResp
        PageResp<DailyTrainTicketQueryResp> resp= new PageResp<>();
        //放数据
        resp.setTotal(dailyTrainTicketPageInfo.getTotal());
        resp.setList(queryResps);


        return resp;
    }

    public void delete(Long id){
        dailyTrainTicketMapper.deleteByPrimaryKey(id);
    }


    //生成余票信息
    @Transactional
    public void dailyTrainCode(DailyTrain dailyTrain, Date date, String trainCode){
        LOG.info("-------------------------余票开始生成---------------------");
        //删除原有的余票信息
        DailyTrainTicketExample dailyTrainTicketExample = new DailyTrainTicketExample();
        dailyTrainTicketExample.createCriteria().andDateEqualTo(date).andTrainCodeEqualTo(trainCode);
        dailyTrainTicketMapper.deleteByExample(dailyTrainTicketExample);
        //获取这车次火车的所有车站信息
        List<TrainStation> trainStations = trainStationService.selectByCode(trainCode);
        //非空校验
        if(CollUtil.isEmpty(trainStations)){
            LOG.info("改车次没有站信息，结束");
        }
        DateTime now = DateTime.now();
        //座位数量信息
        int ydz = dailyTrainSeatService.countSeat(date, trainCode, SeatTypeEnum.YDZ.getCode());
        int edz = dailyTrainSeatService.countSeat(date, trainCode, SeatTypeEnum.EDZ.getCode());
        int rw = dailyTrainSeatService.countSeat(date, trainCode, SeatTypeEnum.RW.getCode());
        int yw = dailyTrainSeatService.countSeat(date, trainCode, SeatTypeEnum.YW.getCode());
        //有车次信息就要插入余票信息
        for (int i = 0; i < trainStations.size(); i++) {
            //获取出发站
            TrainStation trainStart = trainStations.get(i);
            //定义初始公里
            BigDecimal sumKm = BigDecimal.ZERO;
            for (int j = i + 1; j < trainStations.size(); j++) {
                //获取目的站
                TrainStation trainEnd = trainStations.get(j);
                //车站公里数加
                sumKm = sumKm.add(trainEnd.getKm());
                //填写余票信息
                DailyTrainTicket dailyTrainTicket = new DailyTrainTicket();
                dailyTrainTicket.setId(SnowUtil.getSnowflakeNextId());
                dailyTrainTicket.setDate(date);
                dailyTrainTicket.setTrainCode(trainCode);
                dailyTrainTicket.setStart(trainStart.getName());
                dailyTrainTicket.setStartPinyin(trainStart.getNamePinyin());
                dailyTrainTicket.setStartTime(trainStart.getOutTime());
                dailyTrainTicket.setStartIndex(trainStart.getIndex());
                dailyTrainTicket.setEnd(trainEnd.getName());
                dailyTrainTicket.setEndPinyin(trainEnd.getNamePinyin());
                dailyTrainTicket.setEndTime(trainEnd.getInTime());
                dailyTrainTicket.setEndIndex(trainEnd.getIndex());
                //计算票价：票价 = 公里数 *  座位价格 * 车类型的票价系数
                //获取火车类型
                String trainType = dailyTrain.getType();
                //获取火车票价系数
                BigDecimal priceCode = EnumUtil.getFieldBy(TrainTypeEnum::getPriceRate, TrainTypeEnum::getCode, trainType);
                //计算票价
                BigDecimal ydzPrice = sumKm.multiply(SeatTypeEnum.YDZ.getPrice()).multiply(priceCode).setScale(2, RoundingMode.HALF_UP);
                BigDecimal edzPrice = sumKm.multiply(SeatTypeEnum.EDZ.getPrice()).multiply(priceCode).setScale(2, RoundingMode.HALF_UP);
                BigDecimal rwPrice = sumKm.multiply(SeatTypeEnum.RW.getPrice()).multiply(priceCode).setScale(2, RoundingMode.HALF_UP);
                BigDecimal ywPrice = sumKm.multiply(SeatTypeEnum.YW.getPrice()).multiply(priceCode).setScale(2, RoundingMode.HALF_UP);
                dailyTrainTicket.setYdz(ydz);
                dailyTrainTicket.setYdzPrice(ydzPrice);
                dailyTrainTicket.setEdz(edz);
                dailyTrainTicket.setEdzPrice(edzPrice);
                dailyTrainTicket.setRw(rw);
                dailyTrainTicket.setRwPrice(rwPrice);
                dailyTrainTicket.setYw(yw);
                dailyTrainTicket.setYwPrice(ywPrice);
                dailyTrainTicket.setCreateTime(now);
                dailyTrainTicket.setUpdateTime(now);
                dailyTrainTicketMapper.insert(dailyTrainTicket);
            }

        }
    }


    //查询余票数量
    public DailyTrainTicket selectByUnique(Date date,String trainCode,
                                           String start,String end){
        //构造查询条件
        DailyTrainTicketExample dailyTrainTicketExample = new DailyTrainTicketExample();
        dailyTrainTicketExample.createCriteria().andDateEqualTo(date).andTrainCodeEqualTo(trainCode).andStartEqualTo(start).andEndEqualTo(end);
        List<DailyTrainTicket> dailyTrainTickets = dailyTrainTicketMapper.selectByExample(dailyTrainTicketExample);
        if(CollUtil.isNotEmpty(dailyTrainTickets)){
            return dailyTrainTickets.get(0);
        }else {
            return null;
        }
    }
}
